package lockDemo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Ajie
 * @date 8/10/21
 * @function
 * lock.tryLock(）中断测试
 */
public class TryLockInterruptDemo {
    //实例化Lock对象
    Lock lock = new ReentrantLock();

    /**
     * @param args
     */
    public static void main(String[] args) {
        //实例化本类对象，目的是调用runThread方法
        TryLockInterruptDemo tl = new TryLockInterruptDemo();
        //匿名对象创建线程1，并重写run方法，启动线程
        Thread thread = new Thread(() -> tl.runThread(Thread.currentThread()),"thread origin");
        thread.start();
        new Thread(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("thread.interrupt()");
                thread.interrupt();
//                    tl.lock.lockInterruptibly();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"thrad 1").start();

        //匿名对象创建线程2，并重写run方法，启动线程
        new Thread(() -> {
            System.out.println("thread 2 start");
            tl.runThread(Thread.currentThread());
        },"thread 2").start();


    }

    //线程共同调用方法
    public void runThread(Thread t) {
        long startTIme = System.currentTimeMillis();
        //lock对象调用trylock()方法尝试获取锁
        try {
            System.out.println("线程" + t.getName() + "等待获取锁");
            if (lock.tryLock(5000, TimeUnit.MILLISECONDS)) {//TODO 指定时间
                //获锁成功代码段
                System.out.println("线程" + t.getName() + "获取锁成功");
                try {
                    //执行的代码
                    while ((System.currentTimeMillis()-startTIme)<4000){

//                        System.out.println("doing...");
                    };
                    System.out.println("线程" + t.getName() + "执行 完毕");
//                    Thread.sleep(4000);
                } catch (Exception e) {
                    //异常处理内容，比如中断异常，需要恢复等
                    System.err.println("exception :线程" + t.getName());
                    e.printStackTrace();
                } finally {
                    //获取锁成功之后，一定记住加finally并unlock()方法,释放锁
                    System.out.println("线程" + t.getName() + "释放锁");
                    lock.unlock();
                }
            } else {
                //获锁失败代码段
                //具体获取锁失败的回复响应
                System.out.println("线程" + t.getName() + "获取锁失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
